package com.hwpt.chesedemo;

import org.junit.Test;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.*;

/**
 * Stockfish API 测试类 - 修复版
 */
public class StockfishApiTest {

    private static final String STOCKFISH_API_URL = "https://stockfish.online/api/s/v2.php";
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();

    @Test
    public void testStockfishApiWithPGN() {
        // 测试FEN位置 - 初始位置
        String testFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

        try {
            String response = callStockfishApi(testFen, 10);
            assertNotNull("API响应不应为null", response);
            System.out.println("Stockfish API 响应: " + response);

            // 检查响应是否包含有效内容
            assertTrue("响应应包含有效数据", response.length() > 10);

        } catch (Exception e) {
            fail("API调用失败: " + e.getMessage());
        }
    }

    @Test
    public void testComplexPosition() {
        // 复杂局面测试
        String complexFen = "rn1qkbnr/pp2pppp/2p5/3p4/3P1B2/2N5/PPP1PPPP/R2QKBNR w KQkq - 0 1";

        try {
            String response = callStockfishApi(complexFen, 12);
            assertNotNull("API响应不应为null", response);
            System.out.println("复杂局面分析结果: " + response);

        } catch (Exception e) {
            System.out.println("复杂局面测试失败: " + e.getMessage());
        }
    }

    @Test
    public void testYourProvidedPosition() {
        // 你日志中出现的局面
        String yourFen = "rnbqkbnr/pppppppp/8/8/7P/8/PPPPPPP1/RNBQKBNR b KQkq - 0 1";

        try {
            String response = callStockfishApi(yourFen, 8);
            assertNotNull("API响应不应为null", response);
            System.out.println("你的局面分析结果: " + response);

        } catch (Exception e) {
            System.out.println("你的局面测试失败: " + e.getMessage());
        }
    }

    @Test
    public void testMidgamePosition() {
        // 中局测试
        String midgameFen = "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/3P1N2/PPP2PPP/RNBQK2R b KQkq - 0 1";

        try {
            String response = callStockfishApi(midgameFen, 15);
            assertNotNull("API响应不应为null", response);
            System.out.println("中局分析结果: " + response);

        } catch (Exception e) {
            System.out.println("中局测试失败: " + e.getMessage());
        }
    }

    @Test
    public void testEndgamePosition() {
        // 残局测试
        String endgameFen = "8/8/8/8/4k3/8/4K3/8 w - - 0 1";

        try {
            String response = callStockfishApi(endgameFen, 5);
            assertNotNull("API响应不应为null", response);
            System.out.println("残局分析结果: " + response);

        } catch (Exception e) {
            System.out.println("残局测试失败: " + e.getMessage());
        }
    }

    /**
     * 调用Stockfish API - 修复版，不使用JSON库
     */
    private String callStockfishApi(String fen, int depth) throws IOException {
        // 手动构建JSON字符串，避免使用JSONObject
        String jsonBody = String.format("{\"fen\":\"%s\",\"depth\":%d}", fen, depth);

        RequestBody body = RequestBody.create(
                jsonBody,
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url(STOCKFISH_API_URL)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("User-Agent", "CheseDemo-Test/1.0")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("HTTP错误: " + response.code() + " - " + response.message());
            }

            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return responseBody.string();
            } else {
                throw new IOException("响应体为空");
            }
        }
    }

    /**
     * 测试网络连接性
     */
    @Test
    public void testNetworkConnectivity() {
        try {
            Request request = new Request.Builder()
                    .url("https://stockfish.online/")
                    .head()
                    .build();

            try (Response response = client.newCall(request).execute()) {
                assertTrue("应能连接到服务器", response.isSuccessful() || response.code() < 500);
                System.out.println("网络连接测试: HTTP " + response.code());
            }
        } catch (Exception e) {
            System.out.println("网络连接测试失败: " + e.getMessage());
        }
    }

    /**
     * 测试API端点可用性
     */
    @Test
    public void testApiEndpoint() {
        String simpleFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

        try {
            String result = callStockfishApi(simpleFen, 5);
            assertNotNull("API端点应返回数据", result);
            System.out.println("API端点测试成功: " + (result.length() > 100 ? result.substring(0, 100) + "..." : result));

        } catch (Exception e) {
            System.out.println("API端点测试失败: " + e.getMessage());
            System.out.println("请检查:");
            System.out.println("1. 网络连接是否正常");
            System.out.println("2. Stockfish在线服务是否可用");
            System.out.println("3. API URL是否正确: " + STOCKFISH_API_URL);
        }
    }

    /**
     * 测试错误处理
     */
    @Test
    public void testErrorHandling() {
        // 测试无效的FEN
        String invalidFen = "invalid_fen_string";

        try {
            String result = callStockfishApi(invalidFen, 5);
            System.out.println("无效FEN响应: " + result);
            // 即使FEN无效，API也可能返回某种响应，所以不标记为失败

        } catch (Exception e) {
            System.out.println("错误处理测试 - 预期中的错误: " + e.getMessage());
        }
    }
}